package com.wdy.golden.tinysql.proxy;
 
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import com.wdy.golden.tinysql.core.ITinysql;
import com.wdy.golden.tinysql.exception.TinySqlException.ImperfectException;
import com.wdy.golden.tinysql.exception.TinySqlException.SqlParseException;
import com.wdy.golden.tinysql.util.TinysqlSpringUtil;
 
/**  
 * @author Dongye_Wu
 * @version: 1.0.0
 * @Description: 动态代理，需要注意的是，这里用到的是JDK自带的动态代理，代理对象只能是接口，不能是类
 * @date 2020年4月10日 下午11:21:30 
 */
public class ServiceProxy<T> implements InvocationHandler {
	@SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(ServiceProxy.class);
	 
	private Class<T> interfaceType;
 
    public ServiceProxy(Class<T> infType) {
        this.interfaceType = infType;
    }
 
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SqlParseException, ImperfectException {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this,args);
        }
//        log.debug("proxy class name is [{}]", proxy.getClass().getName());
//        log.debug("interfaceType class name is [{}]", this.interfaceType.getClass().getName());
        
        ITinysql tinysqlBean = TinysqlSpringUtil.getBean("tinysqlKeeper", ITinysql.class);
        Assert.notNull(tinysqlBean, "[Tinysql] get bean tinysqlKeeper must not be null");
        return tinysqlBean.executeSql(interfaceType, method, args);
    }
}